﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Core.Interfaces.Search;

using mvcForum.Web.Controllers;
using mvcForum.Web.Extensions;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAdmin.Controllers {

	public class SearchController : ForumAdminBaseController {
		private readonly IEnumerable<ISearchConfigurationController> controllers;
		private readonly IEnumerable<IIndexer> indexers;
		private readonly IConfiguration config;

		public SearchController(IWebUserProvider userProvider, IContext context, IEnumerable<ISearchConfigurationController> controllers, IEnumerable<IIndexer> indexers, IConfiguration config)
			: base(userProvider, context) {

			this.controllers = controllers;
			this.indexers = indexers;
			this.config = config;
		}

		public ActionResult Index() {
			return View(this.controllers);
		}

		[HttpPost]
		public ActionResult Index(Boolean index) {
			if (index) {
				foreach (IIndexer idx in this.indexers) {
					idx.Clear();
				}

				IRepository<Core.Forum> forumRepo = this.GetRepository<Core.Forum>();
				foreach (Core.Forum forum in forumRepo.ReadAll().ToList()) {
					foreach (Topic topic in forum.Topics.Where(t => t.Flag != TopicFlag.Quarantined && t.Flag != TopicFlag.Deleted).ToList()) {
						foreach (IIndexer idx in this.indexers) {
							idx.Index(topic);
							// We don't need deleted posts, no matter what, in the search index!
							idx.BulkIndex(topic.Posts.Visible(this.config).Where(p => p.Position > 0));
						}
					}
				}
			}
			return View(this.controllers);
		}
	}
}